package com.xudow.app.ui.task;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;

import com.activeshare.edu.ucenter.common.messages.Message;
import com.activeshare.edu.ucenter.models.base.AuthRole;
import com.jude.utils.JUtils;
import com.umeng.message.UmengRegistrar;
import com.xudow.app.Config;
import com.xudow.app.XApplication;
import com.xudow.app.dynamicstate_old.data.RongYunModel;
import com.xudow.app.model.SimpleUser;
import com.xudow.app.util.PrefUtils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.RedirectStrategy;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.springframework.http.HttpStatus;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.xudow.app.util.LogUtils.LOGE;
import static com.xudow.app.util.LogUtils.makeLogTag;

/**
 * Login task
 *
 * @author lukecheng
 */
public class LoginTask extends AsyncTask<HashMap<String, String>, Void, Void> {
    private static final String TAG = makeLogTag(LoginTask.class);

    //登陆地址
    private static final String LOGIN_URL = Config.BASE_URL + Config.LOGIN_URL;

    public static final int LOGIN_SUCCESS = 0;
    public static final int LOGIN_FAIL = 1;
    public static final int LOGIN_ERROR = 2;

    private Context context;
    private Handler loginHandler;

    public LoginTask(Context context, Handler loginHandler) {
        this.context = context;
        this.loginHandler = loginHandler;
    }

    private void sendErrorMessage() {
        android.os.Message message = new android.os.Message();
        message.what = LOGIN_ERROR;
        loginHandler.sendMessage(message);
    }

    @Override
    protected Void doInBackground(HashMap<String, String>... parameters) {
        JUtils.Log("start Login");
        // 声明重定向策略对象
        RedirectStrategy redirectStrategy = new LaxRedirectStrategy();
        HttpClient httpClient = HttpClients.custom().setRedirectStrategy(redirectStrategy).build();

        CookieStore cookieStore = new BasicCookieStore();
        HttpContext clientContext = new BasicHttpContext();
        clientContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpPost httpPost = new HttpPost(LOGIN_URL);
        httpPost.setHeader("mobile", "true");
        httpPost.setHeader("phoneType","2");
        httpPost.setHeader("tokenUmeng", UmengRegistrar.getRegistrationId(context));

        String username = parameters[0].get("username");
        String password = parameters[0].get("password");

        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", username));
        nvps.add(new BasicNameValuePair("password", password));

        //nvps.add(new BasicNameValuePair("sourceid",0+""));
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            LOGE(TAG, e.getMessage());
        }

        try {
            HttpResponse response = httpClient.execute(httpPost, clientContext);
            int status = response.getStatusLine().getStatusCode();
            JUtils.Log("finish Login request"+status);

            if (HttpStatus.OK.value() == status) {
                String result = EntityUtils.toString(response.getEntity());
//                LOGE(TAG, "result = " + result);
//                Log.i("lslogin","result>>>>>"+result);
                JSONTokener jsonParser = new JSONTokener(result);
                try {
                    JSONObject jsonObject = (JSONObject) jsonParser.nextValue();

                    Message msg = new Message();
                    msg.setErrorCode(jsonObject.getString("errorCode"));
                    msg.setResult(jsonObject.getString("result"));
                    msg.setErrorMessage(jsonObject.getString("errorMessage"));

                    android.os.Message message = new android.os.Message();

                    if ("0".equals(msg.getResult())) {
                        //登陆成功
                        RongYunModel.getInstance().connectRongYun1(jsonObject.getString("tokenRongcloud"));

                        XApplication application = (XApplication) context.getApplicationContext();
                        application.setCookieStore(cookieStore);

                        //保存用户信息到Preference
                        SimpleUser simpleUser = new SimpleUser();
                        simpleUser.setUsername(username);
                        simpleUser.setPassword(password);
                        //保存融云 token
                        application.setTokenRongcloud(jsonObject.getString("tokenRongcloud"));
                        //保存用户是否提交兴趣
                        boolean has=false;
                        if ("1".equals(jsonObject.get("hasAttentionType"))||1==jsonObject.getInt("hasAttentionType"))
                            has=true;
                        LOGE("login","hasattentionType"+has);
                        application.setHasAttentionType(has);
                        PrefUtils.saveUserInfo(context, simpleUser);
                        PrefUtils.setPrefLoginStatus(context, true);

                        //角色
                        List<AuthRole> roles = new ArrayList<AuthRole>();

                        JSONArray roleArr = jsonObject.getJSONArray("roles");
                        for (int i = 0; i < roleArr.length(); i++) {
                            JSONObject roleJSON = roleArr.getJSONObject(i);

                            AuthRole role = new AuthRole();
                            role.setAbbreviation(roleJSON.getString("abbreviation"));
                            role.setDescription(roleJSON.getString("description"));
                            role.setId(roleJSON.getLong("id"));
                            role.setName(roleJSON.getString("name"));

                            roles.add(role);
                        }

                        application.setRoles(roles);
                        JUtils.Log("complete Login");

                        message.what = LOGIN_SUCCESS;
                    } else {
                        //登录失败
                        Bundle bundle = new Bundle();
                        bundle.putString("errorMessage", msg.getErrorMessage());

                        message.what = LOGIN_FAIL;
                        message.setData(bundle);
                    }

                    loginHandler.sendMessage(message);
                } catch (JSONException e) {
                    LOGE(TAG, e.getMessage());
                }
            } else {
                //登录失败
                sendErrorMessage();
            }
        } catch (IOException e) {
            LOGE(TAG, e.getMessage());

            sendErrorMessage();
        }

        return null;
    }
}
